$(function(){
    var $cartList = $("#cartList");
    var $numberIpt = $cartList.find(".js-number-input");
    var $check = $cartList.find(".js-check");
    var $checkAll = $("#checkAll");

    $(document).on("click", ".js-goods-cart", function(e){
        var $target = $(e.target);

        if($target.hasClass("js-number-sub")){
            NumberSub($target);
        }
        else if($target.hasClass("js-number-plus")){
            NumberPlus($target);
        }
        else if($target.hasClass("js-remove-btn")){
            RemoveGoods($target);
        }
    });

    $numberIpt.on("input propertychange", function(){
        var $this = $(this);

        OptionIpt($this);
    });
	
	$numberIpt.trigger("input");//初始化

    $(document).on("click", "#cartNav", function(e){
        var $target = $(e.target);

        if($target.hasClass("js-remove-all")){
            RemoveSelected();
        }
        else if($target.hasClass("js-settle-accounts")){
            SettleAccounts();
        }
    });

    $check.on("click", function(){
        var $this = $(this);

        SelectedGoods($this);
    });
    $checkAll.on("click", function(){
        var $this = $(this);

        CheckAll($this);
    });
});

//数量减
function NumberSub(element) {
    var $parent = element.closest(".js-goods-cart");
    var $ipt = $parent.find(".js-number-input");
    var iptValue = parseInt($ipt.val());

    if(!isNaN(iptValue)){
        iptValue--;
        if(iptValue <= 1){
            iptValue = 1;
            element.addClass("mallui_number-disabled");
        }
        $ipt.val(iptValue);
    }

    getSubtotal($parent);
    getTotal(); //更新合计
}

//数量加
function NumberPlus(element) {
    var $parent = element.closest(".js-goods-cart");
    var $ipt = $parent.find(".js-number-input");
    var $subElement = $parent.find(".js-number-sub");
    var iptValue = parseInt($ipt.val());

    if(!isNaN(iptValue)){
        console.log(iptValue);
        iptValue++;
        $ipt.val(iptValue);
        $subElement.removeClass("mallui_number-disabled");
    }

    getSubtotal($parent);
    getTotal(); //更新合计
}

//操作数量输入框
function OptionIpt(input){
    var $subElement = input.prev(".js-number-sub");
    var $parent = input.closest(".js-goods-cart");
    var iptValue = parseInt(input.val());

    if(!isNaN(iptValue)){
        if(iptValue < 1) {
            input.val(1);
            $subElement.addClass("mallui_number-disabled");
        }
        else if(iptValue == 1){
            $subElement.addClass("mallui_number-disabled");
        }
        else{
            $subElement.removeClass("mallui_number-disabled");
        }
    }

    getSubtotal($parent);
    getTotal(); //更新合计
}

//删除当前商品
function RemoveGoods(element){
    var $parent = element.closest(".js-goods-cart");

    $.modal({
        title: "温馨提示",
        text: "该商品挺抢手，确认删除吗",
        buttons: [
            { text: "去意已决", onClick: function(){
                $parent.remove();
                getTotal(); //更新合计
				var ids = [];
				ids.push($parent.find(".weui_check_label--itemId").attr("id"));
				$.ajax({
					url: "delCart",
					type: "post",
					dataType: 'json',
					data: {
						ids: JSON.stringify(ids)
					},
					success: function(){
                        var len = $("#cartList").find(".js-goods-cart").length;

                        if(len === 0){
                            location.href = "emptyCart";
                        }
                        
                        cartCnt(); //重新计算购物车数量
					},
					error: function(xhr, type, errorThrown) {
						//异常处理；
						$.alert("请稍后再试！");
					}
				});
            } },
            { text: "再想想", className: "default", onClick: function(){} }
        ]
    });
}

//全选
function CheckAll(){
    var $cartList = $("#cartList");
    var $checkAllBox = $("#checkAll");
    var $checkBox = $cartList.find(".weui_check");

    if($checkAllBox.prop("checked")){
        $checkBox.prop("checked", true);
    }
    else{
        $checkBox.prop("checked", false);
    }

    $cartList.find(".js-goods-cart").each(function() {
        getSubtotal($(this));
    });
    getTotal(); //更新合计
}

//单选
function SelectedGoods(element){
    var $cartList = $("#cartList");
    var $checkAllBox = $("#checkAll");
    var $checkBox = $cartList.find(".weui_check");
    var $parent = element.closest(".js-goods-cart");
    var len = $cartList.find(".weui_check").length;
    var checkedLen = $cartList.find(".weui_check:checked").length;

    if(checkedLen == len){
        $checkAllBox.prop("checked", true);
    }
    else{
        $checkAllBox.prop("checked", false);
    }

    getSubtotal($parent);
    getTotal(); //更新合计
}


//删除选中
function RemoveSelected(){
    var $cartList = $("#cartList");
    var checkedLen = $cartList.find(".weui_check:checked").length;

    if(checkedLen > 0){
        $.modal({
            title: "温馨提示",
            text: "该商品挺抢手，确认删除吗",
            buttons: [
                { text: "去意已决", onClick: function(){
                    var ids = [];
                    $("#cartList").find(".weui_check:checked").each(function(){
                        var _this = $(this);
                        ids.push(_this.closest(".weui_check_label--itemId").attr("id"));
                        _this.closest(".js-goods-cart").remove();
                    });
                    getTotal(); //更新合计
                    $.ajax({
                        url: "delCart",
                        type: "post",
                        dataType: 'json',
                        data: {
                            ids: JSON.stringify(ids)
                        },
                        success: function(){
                            var len = $("#cartList").find(".js-goods-cart").length;

                            if(len === 0){
                                location.href = "emptyCart";
                            }
                            
                            cartCnt(); //重新计算购物车数量
                        },
                        error: function(xhr, type, errorThrown) {
                            //异常处理；
                            $.alert("请稍后再试！");
                        }
                    });
                } },
                { text: "再想想", className: "default", onClick: function(){} }
            ]
        });
    }
    else{
        $.alert("请选择商品");
    }
}

//计算单行价格
function getSubtotal(parent){
    var unitPrice = parseFloat(parent.find(".js-unit-price").text());
    var num = parseInt(parent.find(".js-number-input").val());
    var subtotal = 0;

    subtotal = parseInt(num) * parseFloat(unitPrice).toFixed(2);
    // console.log(subtotal);

    parent.data("subtotal", subtotal);
}

//更新合计
function getTotal(){
    var $settleAccounts = $("#settleAccounts");
    var $totalPrice = $("#totalPrice");
    var total = 0;
    //var freight = 7; //运费
    var freight = 0; //运费

    $("#cartList").find(".weui_check").each(function(){
        if(this.checked){
            var subtotal = $(this).closest(".js-goods-cart").data("subtotal") || 0;
            // console.log(subtotal);

            total += subtotal;
            // console.log(total);
            $settleAccounts.addClass("mallui_btn_enable");
			$settleAccounts.prop("disabled", false);
        }
    });
    if(total == 0){
        $settleAccounts.removeClass("mallui_btn_enable");
		$settleAccounts.prop("disabled", true);
    }
    else{
        total = total + freight;
    }
    $totalPrice.text(total.toFixed(2));
}

//结算
function SettleAccounts(){
	var goodsItemIds = "";
	var counts = "";
	var cartIds = "";

    $("#cartList").find(".weui_check:checked").each(function(){
		var _this = $(this);
		var goodsItem = _this.closest(".js-goods-cart");
		var number = parseInt(goodsItem.find(".js-number-input").val());
		var id = goodsItem.attr("id");
		var cartId = _this.closest(".weui_check_label--itemId").attr("id");

		if(!isNaN(number)){
            counts += number + ",";
        }
        else{
            $.alert("请输入商品数量");
            return false;
        }
		goodsItemIds += id + ",";
		cartIds += cartId + ",";
	});
	
	if( cartIds.length > 0 ){
		cartIds = cartIds.substring(0,cartIds.lastIndexOf(","));
		sessionStorage.setItem("cartIds", cartIds);
	}
	
	if( goodsItemIds.length > 0 && counts.length > 0 ){
		goodsItemIds = goodsItemIds.substring(0,goodsItemIds.lastIndexOf(","));
		counts = counts.substring(0,counts.lastIndexOf(","));
		location.href = "orderConfirm?goodsItemIds=" + goodsItemIds + "&counts=" + counts;
	}
}